const express = require('express')
const router = express.Router()
const jwt = require('jsonwebtoken');
const db = require('../db')
let { md5 } = require('utility')

// 验证
router.use((req, res, next) => {
    let { username, password } = req.body
    if (/\S{6,12}/.test(password)) {
        next()
    } else {
        next('密码必须是6-12位切不能有空格')
    }
})
// 注册
router.post('/reguser', (req, res) => {
    let {username,password} = req.body
    password = md5(password)
    db(`select * from user where username='${username}'`, (e, r) => {
        if (e) throw e;
        // console.log(r)
        // 查到，非空数组；否则空
        if (r.length >0 ) {
            res.send({status:1,message:'用户名以存在'})
        } else {
            let sql = `insert into user set username='${username}',password='${password}'`
            db(sql, (err, result) => {
                if (err) throw err
                res.send({ status: 0, message: '注册成功' })
            })
        }
    })
    
})

// 登录
router.post('/login', (req, res) => {
    // 接受客户端提交的账号和密码
    let username = req.body.username;
    let password = md5(req.body.password);
    // 验证密码是否正确
    db(`select * from user where username='${username}' and password='${password}'`, (err, result)=>{
        if (err) throw err
        if (result.length > 0) {
            // 登录成功，生成token
            // 在token中保存用户的id
            // token前必须加 “Bearer ”，注意空格
            let token = 'Bearer ' + jwt.sign({ id: result[0].id }, 'sfsws23s', { expiresIn: '2h' });
            res.send({ status: 0, message: '登录成功', token })
          } else {
            res.send({ status: 1, message: '账号或密码错误' })
          }
    })
   

})

router.use((err, req, res, next) => {
    res.send({status:1,message:err})
})
module.exports = router;

